
clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_firststage.log"	, replace 
use 		 "$datapath/A3_age55data_WC.dta"

*Keeping date at notification 
keep  if eventtime_def==0

{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*

gen diff= (inkom_dat - ankomst_dat )/30
bys varselid : egen mindiff = min(diff)
bys varselid : egen maxdiff = max(diff)
winsor2  diff, replace

bys varselid : egen maxabove55 = max(treat) 

{ // Graph of delay
*===============================================================================
preserve
	gen freq = 1 
	local outcome "diff"
	
	keep if mindiff!=maxdiff 	// keep notifications with no common indiviual notificaiton date
	*==========
	xtset   varselid
	*==========
	*reg 	`outcome'  	$instrument	$linear  $covariets 		, cluster(varselid) 
	eststo: xtreg 	`outcome'  	$instrument	$linear  $covariets 		, cluster(varselid) fe nonest
	local b  = round(_b[$instrument] ,.001)
	local se = round(_se[$instrument] ,.001)
	
	*Residulize year*moth fixed effects
	qui areg `outcome' $covariets if e(sample)==1, absorb(varselid)
	predict e, residuals
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `outcome'_bin = mean(`outcome')
	qui tab runvar bin
	
	
	
	collapse (mean) nottime_def `outcome'_bin (sum) freq, by(runvar bin treat)
	replace runvar = runvar*12

	twoway  (scatter `outcome'_bin bin , ms(o) mcolor(black)) ///
		(lfit    `outcome' runvar [aweight=freq] if treat==0, lcolor(black)) /// 
		(lfit    `outcome' runvar [aweight=freq] if treat==1, lcolor(black)) ///
	, xline( 0 , lcolor(black) lpattern(dash))  legend(off) graphregion(color(white)) ///
	 ytitle("Delay (months)") xtitle("Normalized age (months)") title("") ///
	 xscale(r(-36 36)) xlab(-36(12)36) name(lfit,replace) ///
	 text(5.2 -12   "{&beta}=0`b'**" "(0`se')"  ,place(right)  )
	graph export "$agegraphpath/FS/FS_delay_binned_within.pdf" ,replace

restore				
	
}
*
bys maxabove55 : sum diff 
{ // Table of delay
*===============================================================================
eststo clear
xtset   varselid

qui eststo : reg diff  	$instrument	$linear  $covariets ,cluster(varselid)	
qui eststo : xtreg diff  	$instrument	$linear  $covariets ,cluster(varselid)	fe nonest
estadd 	local disfe " $ \checkmark $ " 	, replace
qui eststo : reg diff  	$instrument	$linear  $covariets if mindiff==maxdiff ,cluster(varselid) 
qui eststo : reg diff  	$instrument	$linear  $covariets if mindiff!=maxdiff ,cluster(varselid)  
qui eststo : xtreg diff  	$instrument	$linear  $covariets if mindiff!=maxdiff ,cluster(varselid)  fe nonest	
estadd 	local disfe " $ \checkmark $ " 	, replace

esttab ,  se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) keep($instrument  _cons )
esttab using "$agetablepath/FS/tab_delay.tex", replace keep($instrument _cons ) booktabs nodepvars noobs nomtitles nonumbers ///
varlabels(treat "Above 55" _cons "Control mean") se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) ///
stats(disfe  r2  N, fmt(%9.0g  %9.3f   %9.0fc) /// 
labels("Displacement FE"  "R2"  "\# observations")) ///
title("Effects if MN on Delay of Notice  \label{tab:delay}" ) ///
mlabels("(1)" "(2)" "(3)" "(4)" "(5)") ///
nonotes 

}
*

{ // Create dataset of earnings from consecutive layoffs
*===============================================================================
use "$datapath/A3_gen_empmark.dta",clear
gen eventtime_ankomst = date - ym(year(ankomst_dat), month(ankomst_dat)) 
keep if inrange(eventtime_ankomst,-12,48)
merge m:1 persid firmid varselid using "$datapath/A1_varseldata.dta", keepusing(plantid)
drop if _merge==2
drop _merge

{ // Merge on notifications (first and second)
*===============================================================================
merge m:1 plantid ankomst_dat using "$datapath/multiplenotif.dta", update replace
sum ankomst_dat if _merge==2,format d  // most dispalcements are late periods...
drop if _merge<3
drop _merge
}
*
{ // Merge on those second notifications that are followed by a third
*===============================================================================
*indicate which observatrions to duplicate
merge m:1 plantid ankomst_dat using "$datapath/multiplenotif_fill.dta", keepusing(fill) update replace
drop if _merge==2 
drop _merge

expand 2 if fill==1, gen(newfill)
replace fill=0 if newfill==1

merge m:1 plantid ankomst_dat fill using "$datapath/multiplenotif_fill.dta", keepusing(newspell nrspell) update replace
drop if _merge==2
drop _merge
}
*
egen id = group( plantid newspell) 
{ // Fix white-collar indicator
*===============================================================================
count if eventtime_ankomst==0
count if WC==. & eventtime_ankomst==0
replace WC = 1 if utbniv>=6 & WC==.
bys plantid ankomst_dat newspell nrspell eventtime_ankomst  : egen WCmode= mode(WC) 
replace WC=WCmode if WC==.
replace WC=0 if WC==.

}
*
{ // Generate seniority
*===============================================================================
*Overall seniority (no WC division)
bys plantid ankomst_dat newspell nrspell eventtime_ankomst (tenureatnot age_def persid) : gen seniority = _n 		// =1 lowest tenure 
bys plantid newspell eventtime_ankomst (ankomst_dat nrspell tenureatnot age_def persid) : gen overallseniority = _n 	// =1 lowest tenure 
bys plantid newspell eventtime_ankomst nrspell : egen minsen=min(seniority)
bys plantid newspell eventtime_ankomst nrspell : egen maxsen=max(seniority)

gen x_maxsen_first = maxsen if nrspell==1
bys plantid newspell eventtime_ankomst  : egen maxsen_first = max(x_maxsen_first)
gen overallseniority2 = cond(nrspell==1,seniority,seniority+maxsen_first)		// missings generated due to duplicates notificaitons that have no nrspell==1

*Seniority by WC
bys plantid ankomst_dat newspell nrspell eventtime_ankomst WC (tenureatnot age_def persid) : gen WCseniority = _n 		// =1 lowest tenure 
bys plantid newspell eventtime_ankomst WC (ankomst_dat nrspell tenureatnot age_def persid) : gen WCoverallseniority = _n 	// =1 lowest tenure 
bys plantid newspell eventtime_ankomst nrspell WC: egen WCminsen=min(WCseniority)
bys plantid newspell eventtime_ankomst nrspell WC: egen WCmaxsen=max(WCseniority)

gen x_WCmaxsen_first = WCmaxsen if nrspell==1
bys plantid newspell eventtime_ankomst  WC : egen WCmaxsen_first = max(x_WCmaxsen_first)
gen WCoverallseniority2 = cond(nrspell==1,WCseniority,WCseniority+WCmaxsen_first)

*Running variables
gen runvar = overallseniority2 - maxsen_first
gen WCrunvar = WCoverallseniority2 - WCmaxsen_first

drop x*
}
*
{ // Generate variables
*===============================================================================
*Number of WC workers
bys plantid newspell eventtime_ankomst nrspell : egen N_WC=total(WC)
*Number of notified first notification
bys plantid newspell eventtime_ankomst (nrspell) : gen xantvars_first = antvars if _n==1 
bys plantid newspell eventtime_ankomst (nrspell) : egen antvars_first = max(xantvars_first)
*Number of notified second notification
bys plantid newspell eventtime_ankomst (nrspell) : gen xantvars_second = antvars if _n==_N
bys plantid newspell eventtime_ankomst (nrspell) : egen antvars_second = max(xantvars_second)
*Time between first and second notification
bys plantid newspell eventtime_ankomst (nrspell) : gen xdiff_ankomst = ankomst_dat_diff if _n==1 
bys plantid newspell eventtime_ankomst (nrspell) : egen diff_ankomst = max(xdiff_ankomst)
*Date of first notification
bys plantid newspell eventtime_ankomst (nrspell) : gen xfirst_date = ankomst_dat if _n==1 
bys plantid newspell eventtime_ankomst (nrspell) : egen first_date = max(xfirst_date)
*Generate eventtime relative to first notification
gen first_date_ym = ym(year(first_date),month(first_date))
gen eventtime_first_date =  date - first_date_ym

*Earnings
replace annual_w2=0 if otherfirm==0
replace annual_w2=0 if annual_w2<0
bys lopnr (eventtime_first_date) : gen sum_w2 = sum(annual_w2) if eventtime_first_date>=0

replace annual_w1=0 if atfirm==0
bys lopnr (eventtime_first_date) : gen sum_w2_atfirm = sum(annual_w1) if eventtime_first_date>=0

replace annual_w2=0 if otherfirm2==0
bys lopnr (eventtime_first_date) : gen sum_w2_v2 = sum(annual_w2) if eventtime_first_date>=0

gen x_pre_monthly_w1 = annual_w1 if eventtime_ankomst==0
bys lopnr (eventtime_first_date) : egen pre_monthly_w1 = max(x_pre_monthly_w1)

gen sum_w2_div_prenot		=sum_w2/annual_ear_prenot_def
gen sum_w2_v2_div_prenot	=sum_w2_v2/annual_ear_prenot_def

gen sum_w2_div_monthly_w1 	= sum_w2/pre_monthly_w1
gen sum_w2_v2_div_monthly_w1	= sum_w2_v2/pre_monthly_w1
winsor2 annual_ear_prenot_def,replace
gen sum_w2_div_prenot_win		=sum_w2/annual_ear_prenot_def
gen sum_w2_v2_div_prenot_win	=sum_w2_v2/annual_ear_prenot_def

*De jure notice and its share within the first layoff
gen 	de_jure_NT = .
replace de_jure_NT = 30  	if inrange(tenureatnot ,0,23) 
replace de_jure_NT = 60  	if inrange(tenureatnot ,24,47) 
replace de_jure_NT = 90   	if inrange(tenureatnot ,48,71) 
replace de_jure_NT = 120 	if inrange(tenureatnot ,72,95) 
replace de_jure_NT = 150 	if inrange(tenureatnot ,96,119) 
replace de_jure_NT = 180   	if tenureatnot >=120 & tenureatnot !=. 
replace de_jure_NT = 365 	if  age_def>=55 

gen temp = de_jure_NT<120
bys plantid newspell eventtime_ankomst : egen sharelowdejure = mean(temp) if nrspell==1
bys plantid newspell eventtime_ankomst  : egen maxsharelowdejure = max(sharelowdejure)


drop temp x*
}
*
save "$datapath/B2_consec_layoffs.dta",replace
}
*

gen x_temp = sum_w2_atfirm if  eventtime_first_date==24
bys lopnr : egen yy = max(x_temp)

gen x_temp = sum_w2_atfirm if  eventtime_first_date==24
bys lopnr : egen yy = max(x_temp)

gen anstupp_ym = ym(year(anstupp_dat), month(anstupp_dat))

gen x_leftfirm = atfirm==0 & atfirm[_n+1]==0 if date==anstupp_ym +2
bys lopnr : egen leftfirm=max(x_leftfirm)

gen tenureatnot_sq = tenureatnot^2

bys plantid newspell nrspell eventtime_ankomst : egen maxWC=max(WC)

use "$datapath/B2_consec_layoffs.dta",clear



{ // Graph of earnings between layoffs
*===============================================================================
local outcome "sum_w2_div_monthly_w1"
preserve
	gen above55= age_def>=55 
	*replace `outcome' =`outcome' - yy
	winsor2 `outcome',replace
	keep if eventtime_first_date==12
	*keep if maxWC==0
	*keep if leftfirm==1
	*keep if antvars_first==maxsen_first
	*keep if age_def>55
	*sum difften diffage,d
	*keep if diffage>5 & difften>15
	*keep if WC==0
	
	*keep if N_WC==0
	gen treat = nrspell==2
	gen inter = runvar*treat
	
	keep if year(ankomst_dat)<=2016
	*keep if WC==0
	keep if inrange(runvar,-10,10)
	keep if inrange(diff_ankomst,90,180)
	drop if varselorsak>=5
	sum `outcome' if runvar==0
	
	tab varselkat WC,m
	
	gen age_sq = age^2
	eststo clear
	qui eststo :  reg `outcome' treat runvar inter ,r
	qui eststo :  areg `outcome' treat runvar inter ,r absorb(WC)
	qui eststo :  areg `outcome' treat tenureatnot female age_def age_sq,r absorb(WC)
	 
	eststo :  reg `outcome' treat c.tenureatnot##i.WC female c.age_def##i.WC c.age_sq##i.WC  ,cluster(varselid)
	local b = round(_b[treat],.001)
	local se =round( _se[treat],.001)
	esttab , keep(treat)

	eststo clear
	qui eststo :  reg ankomst_dat treat runvar inter ,r
	qui eststo :  areg ankomst_dat treat runvar inter ,r absorb(WC)
	qui eststo :  areg ankomst_dat treat tenureatnot female age_def age_sq,r absorb(WC)
	qui eststo :  reg ankomst_dat treat c.tenureatnot##i.WC female c.age_def##i.WC c.age_sq##i.WC  ,cluster(varselid)
	esttab , keep(treat) title("Difference in first report")

	
	
	qui reg `outcome' c.tenureatnot##i.WC female c.age_def##i.WC c.age_sq##i.WC  ,r
	predict resid,resid
	qui sum `outcome'
	gen plotoutcome = resid + `r(mean)'
	sum `outcome' if runvar==0
	sum `outcome' if runvar==-1
	count
	gen freq =1
	gcollapse (mean) plotoutcome (sum) freq ,by(runvar nrspell)
	twoway 	(scatter plotoutcome runvar if nrspell==1, mcolor(black) ms(o)) ///
		(scatter plotoutcome runvar if nrspell==2, mcolor(black) ms(o) ) ///
		(lfit plotoutcome runvar [aweight=freq] if nrspell==1, lcolor(black)) ///
		(lfit plotoutcome runvar [aweight=freq] if nrspell==2 ,lcolor(black)) ///
		, xline(0, lpattern(dash) lcolor(black) lstyle(foreground)) ///
		graphregion(color(white)) legend(off) name(q1,replace) ///
		ytitle("Cumulative monhtly earnings since first layoff") xtitle("Normalized seniority") ///
		xscale(r(-10 10)) xlab(-10 -5 `" "-5" "{bf:First layoff}" "'  0 5 `" "5" "{bf:Second layoff}" "' 10) ///
		text(4.5 3 "{&beta}=`b'***" "(0`se')")
		
	graph export "$agegraphpath/RD/RD_delay_`outcome'_t12_withtext_v2.pdf"	,replace
restore	
}
*
